/** 
 * @Title:监听节点是否为leader  
 * @Desription:监听节点是否为leader
 * @Company:CSN
 * @ClassName:LeaderListener.java
 * @Author:Justic
 * @CreateDate:2015-6-30   
 * @UpdateUser:Justic  
 * @Version:0.1 
 *    
 */

package com.justic.zk.quartz.curator.support;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.framework.state.ConnectionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.justic.zk.quartz.curator.ICuratorWrapper;

/**
 * @ClassName: LeaderListener
 * @Description: 监听节点是否为leader
 * @author: Justic
 * @date: 2015-6-30
 * 
 */
public class LeaderListener extends LeaderSelectorListenerAdapter implements Closeable {

	private Logger logger = LoggerFactory.getLogger(LeaderListener.class);

	private ICuratorWrapper curator;

	/**
	 * @param curator
	 */
	public LeaderListener(ICuratorWrapper curator) {
		this.curator = curator;
	}

	/**
	 * @param client
	 * @param connectionState
	 * @see org.apache.curator.framework.state.ConnectionStateListener#stateChanged(org.apache.curator.framework.CuratorFramework,
	 *      org.apache.curator.framework.state.ConnectionState)
	 */
	@Override
	public void stateChanged(CuratorFramework client, ConnectionState connectionState) {
		// for zk server-thread
		logger.info("{} connectionState is=======>>>>{}", curator.getNodeName(), connectionState);
	}

	/**
	 * 
	 * if node is leader(master) then go to here
	 * 
	 * @param arg0
	 * @throws Exception
	 * @see org.apache.curator.framework.recipes.leader.LeaderSelectorListener#takeLeadership(org.apache.curator.framework.CuratorFramework)
	 */
	@Override
	public void takeLeadership(CuratorFramework client) throws Exception {

		// once you take the leader ship
		// and you want hold the leader ship during the whole life of APP1
		// you should use Thread.sleep(Integer.MAX_VALUE)
		// once tha APP1 dead, the other APP (participants) will reElect an new
		// leader
		logger.info("{} is leader now=====>>>>>>>>>>>>>>>", curator.getNodeName());
		curator.setNodeMode(NodeMode.Leader);
		// hold the leader ship during the whole life
		//Thread.sleep(Integer.MAX_VALUE);
		TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
	}

	/**
	 * @throws IOException
	 * @see java.io.Closeable#close()
	 */
	@Override
	public void close() throws IOException {
		curator.close();
	}

}
